//
//  NetworkManager.swift
//  SwiftProject
//
//  Created by qindong on 2022/7/27.
//

import Moya

let disposeBag = DisposeBag()

class NetworkManager: NSObject {
    var networkStatus : Bool = true
    static let manager = NetworkManager()

    private override init() {
        super.init()
        NetworkMonitor.shared.netWorkReachability { [unowned self] status in
            switch status {
            case .reachable:
                networkStatus = true
            default:
                networkStatus = false
            }
        }
    }
    
    /// 请求
    func request<T: HandyJSON>(targetType : MyService,
                               showHud : Bool = true,
                               responseModelType : T.Type,
                               //                                         cacheHandler: ((_ : T)->())? = nil,
                               completionHandler : @escaping(_ : T) -> Void) {
        if showHud {
            self.hudShow()
        }
        provider.rx.request(targetType).asObservable().mappingModel(T.self).subscribe (onNext: { [weak self] result in
            guard let self = self else {
                return
            }
            if showHud {
                self.hudDisMiss()
            }
            completionHandler(result)
        }, onError: { [weak self] error in
            guard let self = self else {
                return
            }
            if showHud {
                self.hudDisMiss()
            }
        }).disposed(by: disposeBag)
    }
    
    /// 下载
    func download(targetType : MyService,
                  showHud : Bool = true,
                  path : String,
                  downloadProgress : @escaping(_ progress : Progress?) -> Void,
                  completionHandler : @escaping(_ result : Bool, _ path : String?) -> Void) {
        if showHud {
            self.hudShow()
        }
        downloadProvider.rx.requestWithProgress(targetType).asObservable().subscribe (onNext: { progress in
            downloadProgress(progress.progressObject)
        }, onError: { [weak self] error in
            guard let self = self else {
                return
            }
            if showHud {
                self.hudDisMiss()
            }
            if DEBUG {
                print("下载失败！\(error.asAFError!.errorDescription!)")
            }
            completionHandler(false, nil)
        }, onCompleted: { [weak self] in
            guard let self = self else {
                return
            }
            if showHud {
                self.hudDisMiss()
            }
            let localLocation: URL = DefaultDownloadDir.appendingPathComponent(path)
            if DEBUG {
                print("下载完毕！保存地址：\(localLocation.absoluteString)")
            }
            completionHandler(true, localLocation.absoluteString)
        }).disposed(by: disposeBag)
    }
    
    func hudShow() {
        KRProgressHUD.show()
    }
    
    func hudDisMiss() {
        KRProgressHUD.dismiss()
        AppDelegate.appDelegate.window?.makeKey()
    }
}

extension ObservableType where Element == Response {
    func mappingModel<T: HandyJSON>(_ type: T.Type) -> Observable<T> {
        flatMap({ (response) -> Observable<T> in
            Observable.just(response.mappingModel(T.self))
        })
    }
}

extension Response {
    func mappingModel<T: HandyJSON>(_ type: T.Type) -> T {
        // 没有数据返回
        if data.count < 1 {
            if let emptyValue = JSONDeserializer<T>.deserializeFrom(json: "{}"){
                return emptyValue
            } else if let emptyValue = JSONDeserializer<T>.deserializeFrom(json: "[{}]"){
                return emptyValue
            }
        }
        // 获取请求response的data转成json
        let jsonString = String(data: data, encoding: .utf8)
        if let model = JSONDeserializer<T>.deserializeFrom(json: jsonString) {
            return model
        }
        return JSONDeserializer<T>.deserializeFrom(json: "{\"status\":\"request error\"}")!
    }
}
